package cn.itsource.basic.aop;

import cn.itsource.system.domain.Log;
import cn.itsource.system.mapper.LogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component //将当前类交给Spring管理
@Aspect //申明当前方法是一个AOP的核心业务类=切面类
public class LogService {
    @Autowired //主要发送请求，系统会自动创建这个对象
    private HttpServletRequest request; //注入请求对象-获取ip和session对象
    @Autowired
    private LogMapper logMapper;
    //只有有@Log注解的方法才作用 - around方法作用到使用了@Logs注解的方法
    @Around("@annotation(cn.itsource.basic.annotation.LogAOP)") //优点：灵活，缺点：要加注解才能记录
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Log log = new Log();

        //通过方法签名获取方法名
        String methodName = joinPoint.getSignature().getName();
        log.setMethodName(methodName);

        //获取ip地址
        String ip = request.getRemoteAddr();
        log.setIp(ip);

        //获取desc内容
        String className = joinPoint.getTarget().getClass().getName(); //获取类名
        String desc = ip + "在" + log.getCreateTime() + "操作了" + className
                + "的" + methodName;
        log.setDesc(desc);
        //执行目标方法 - 如果不返回调用发就接收到null值
        Object result = joinPoint.proceed();

        logMapper.add(log);//将日志信息添加到数据库
        return result;
    }
}
